import { app, BrowserWindow, dialog, ipcMain } from "electron";

let win: BrowserWindow = null;

async function getFilePath () {
  const { canceled, filePaths } = await dialog.showOpenDialog({});
  if (!canceled) {
    return filePaths[0];
  }
}

function getInstallPath () {
  const arr = app.getPath("exe").split("\\");
  arr.pop();
  return arr.join("\\");
}

function download (e, url: string) {
  return new Promise(resolve => {
    win.webContents.downloadURL(url);
    win.webContents.session.on("will-download", (event, item) => {
      item.on("updated", (e, state) => {
        win.webContents.send(
          "message",
          "updated " + state + item.getPercentComplete()
        );
      });
      item.once("done", async (_e, state) => {
        win.webContents.send("message", "done " + state);
        resolve(state);
      });
    });
  });
}

export default function (passedWin: BrowserWindow) {
  win = passedWin;
  ipcMain.handle("getFilePath", getFilePath);
  ipcMain.handle("getInstallPath", getInstallPath);
  ipcMain.handle("download", download);
}
